/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package aso.upna.threads;

import aso.upna.config.ClientConfig;
import aso.upna.information.StreamInfo;
import aso.upna.p2pmessages.FailMessage;
import aso.upna.p2pmessages.OkMessage;
import aso.upna.p2pmessages.PlayMessage;
import aso.upna.p2pmessages.StopMessage;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JProgressBar;

/**
 *
 * @author triki
 */

/*
 * Esta clase es la que se utilizará para conectarse al otro cliente. Cuando
 * su negociacion termine. Esta clase abrirá el hilo UDP para esperar
 * la recepción del flujo (cancion) por parte del otro cliente.
 *
 * La conexion que entablará este hilo es una conexion entre clientes.

 */

public class ClientConnect implements Runnable {

    private ClientConfig conf;
    private int remoteTcpPort;
    private String ip;
    private String toPlay;
    private String user;
    private boolean stop;
    private JProgressBar progress;
    
    public ClientConnect(ClientConfig cfg,String ip,int remoteTCPport,String toPlay,String usr)
    {
        conf = cfg;
        this.ip = ip;
        remoteTcpPort = remoteTCPport;
        this.toPlay = toPlay;
        progress = null;
        user = new String(usr);
        stop = false;
    }

    public ClientConnect(ClientConfig cfg,JProgressBar progress,String ip,int remoteTCPport,String toPlay,String usr)
    {
        conf = cfg;
        this.ip = ip;
        remoteTcpPort = remoteTCPport;
        this.toPlay = toPlay;
        this.progress = progress;
        user = new String(usr);
    }

    public void registerObserver(JProgressBar prog)
    {
        progress = prog;
    }

    public void disconnect()
    {
        stop = true;
    }

    public void run() {

        ObjectInputStream ois = null;
        ObjectOutputStream oos = null;
        String req = null;
        String rep = null;
        Object aux = null;
        StreamInfo inf;
        boolean end = false;

        UdpStream uStream = new UdpStream(conf);
        Thread udpThread = new Thread(uStream);

        try
        {
            
            Socket sock = new Socket(ip, remoteTcpPort);

            oos = new ObjectOutputStream(sock.getOutputStream());
            ois = new ObjectInputStream(sock.getInputStream());

            PlayMessage msg = new PlayMessage(toPlay,user,conf.getUdpPort());
            udpThread.start();

            oos.writeObject(msg);

            try
            {
                aux = ois.readObject();

                if(aux instanceof OkMessage)
                {
                    OkMessage ok = (OkMessage)aux;
                    long p_total = ok.getSize();
                    inf = new StreamInfo(p_total);
                    uStream.registerStreamInfo(inf);

                    long per = 0;

                    while(per < 100 && !stop)
                    {
                        per = inf.getPercetCompleted();

                        if(progress != null)
                        {
                            progress.setValue((int)per);
                        }
                        else
                        {
                            System.out.println("Porcentaje: "+per);
                        }
                        
                        try
                        {
                            Thread.sleep(1000);
                        }
                        catch (InterruptedException ex)
                        {
                            Logger.getLogger(ClientConnect.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }

                    if(true)
                    {
                        System.out.println("Stop command detected");
                        oos.writeObject(new StopMessage());
                        udpThread.interrupt();
                        sock.close();
                        return;
                    }
                    
                    try
                    {
                        udpThread.join();
                        System.out.println("HILO UDP Terminado");
                    }
                    catch (InterruptedException ex)
                    {
                        Logger.getLogger(ClientConnect.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                if(aux instanceof FailMessage)
                {
                    FailMessage fail = (FailMessage)aux;
                    System.out.print("Error. Motivo: "+fail.getMessage());
                    udpThread.interrupt();
                    return;
                }
            }
            catch (ClassNotFoundException ex)
            {
                ex.printStackTrace();
            }
            
            /*if(!end)
            {
                System.out.println("recibido: "+rep);
                String[] parts = rep.split(" ");
                int p_total = Integer.parseInt(parts[1]);
                inf = new StreamInfo(p_total);
                uStream.registerStreamInfo(inf);

                int per = 0;

                while(per < 100)
                {
                    per = inf.getPercetCompleted();

                    if(progress != null)
                    {
                        progress.setValue(per);
                        progress.setString(""+per+"%");
                    }
                    else
                    {
                        System.out.println("Porcentaje: "+per);
                    }

                    try
                    {
                        Thread.sleep(1000);
                    }
                    catch (InterruptedException ex)
                    {
                        Logger.getLogger(ClientConnect.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                try
                {
                    udpThread.join();
                    System.out.println("HILO UDP Terminado");
                }
                catch (InterruptedException ex)
                {
                    Logger.getLogger(ClientConnect.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            System.out.println("Hilo Connect terminado");*/
        } 
        catch (UnknownHostException ex)
        {
            ex.printStackTrace();
        }
        catch (IOException ex)
        {
            ex.printStackTrace();
        }    
    }

}
